using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace MyCompany.WebCrawler.Repositories
{
    public class Repository : IRepository
    {
        private long LastVerification = DateTime.Now.Ticks;

        private TaskQueue queue;
        public TaskQueue Queue { get { return queue; } }

        public Repository()
        {
            queue = new TaskQueue();
        }

        public virtual void Save(string url)
        {
            using (var db = new CrawlerContext())
            {
                Trace.WriteLine("DbSave: " + url);
                db.Urls.Add(new Url()
                {
                    Path = url, 
                    Created = DateTime.Now.Ticks
                });

                db.SaveChanges();
            }
        }

        public string Connection
        {
            get
            {
                using (var db = new CrawlerContext())
                {
                    return db.Database.Connection.ConnectionString;
                }
            }
        }

        public List<string> RemoveDuplicats(List<string> links)
        {
            using (var db = new CrawlerContext())
            {
                var result = new List<string>();

                foreach (var link in links)
                {
                    var dbLink = (from r in db.Urls
                        where r.Path == link
                        select r).FirstOrDefault();

                    if (dbLink == null)
                    {
                        result.Add(link);
                    }
                }

                return result;
            }
        }

        public virtual List<Url> Load()
        {
            using (var db = new CrawlerContext())
            {
                var newLastVerification = DateTime.Now.Ticks;

                var urls = from r in db.Urls
                           where r.Created > LastVerification 
                           select r;

                var result = urls.ToList();
                Trace.WriteLine("DbLoad: " + result.Count);

                LastVerification = newLastVerification;
                return result;
            }
        }

        public void Clean()
        {
            Trace.WriteLine("Clean database up.");
            using (var db = new CrawlerContext())
            {
                db.Database.ExecuteSqlCommand("DELETE FROM Urls");
            }
        }
    }
}